# -*- coding: utf-8 -*-
# 前端到后台的数据处理

import uuid
from pao_python.pao.data import get_date, get_cur_time
from service.enum import SignValue
import json
import random
from service.common import find_data
import requests


# 关联属性
REFERNCE_KEY = {'company_handle_code': 301, 'category_handle_code': 101}
# 不需要保存到proxy的字段
NO_ATTRIBUTE = ['id', 'user_id', 'create_date', 'modify_date',
                'handle_type', 'module_sort', 'qr_code_logo_picture', 'parent_id']

# 创建标识数据处理-存入本地数据库


def get_public_private_attribute(data, handle_type, db=None):
    public_keys = ['id', 'handle_code', 'handle_name', 'handle_type', 'user_id', 'rc_code',
                   'product_type', 'industry_type', 'link_website', 'module_sort', 'qr_code_logo_picture', 'parent_id']
    data['handle_type'] = handle_type
    public_cols = {}
    attribute_data = []
    private_cols = {}
    # reference_cols = []
    # reference_handle = []  # 关联标识
    operate_type = False
    # 获取标识品类属性的关键字，类型，排序等
    sign_value = SignValue['sign_value'].value[handle_type]
    for key in sign_value:
        # 处理提交数据中不存在于模版的值
        if key not in data:
            data[key] = ''
        create_dict = {
            'sign_key': key,
            'sign_type': sign_value[key]['sign_type'],
            'sign_value': data[key],
            'index': sign_value[key]['index'],
            'sign_name': sign_value[key]['sign_name']
        }
        attribute_data.append(create_dict)
    #新建创建id and crate_date
    if ('id' not in data) or data['id'] == '':
        data['id'] = str(uuid.uuid1())
        public_cols['create_date'] = get_cur_time()
        operate_type = True  # 表示新增
        private_cols['date'] = public_cols['create_date']
    for key in data:
        # 存放标识数据表
        if key in public_keys:
            public_cols[key] = data[key]
        # 处理需要保存到proxy和本地类目属性表的数据
        # if key not in NO_ATTRIBUTE:
        #     create_dict = {
        #         'sign_key': key,
        #         'sign_type': sign_value[key]['sign_type'],
        #         'sign_value': data[key],
        #         'index': sign_value[key]['index'],
        #         'sign_name': sign_value[key]['sign_name']
        #     }
        #     attribute_data.append(create_dict)

        # # 创建关联标识数据
        # if key in ['category_handle_code', 'company_handle_code']:
        #     reference_cols.append({
        #         'id': str(uuid.uuid1()),
        #         'handle_id': data['handle_code'],
        #         'ref_handle_id': data[key],
        #         'ref_type': key
        #     })
        #     reference_handle.append(key)
    # 获取当前修改时间
    public_cols['modify_date'] = get_cur_time()
    # 组装保存到本地类目属性表的数据结构
    private_cols = {
        'id': str(uuid.uuid1()),
        'handle_id': public_cols['id'],
        'attribute_data': attribute_data,
        'modify_date': get_cur_time()
    }
    # , 'reference_cols': reference_cols, 'reference_handle': reference_handle
    return {'public': public_cols, 'private': private_cols, 'operate_type': operate_type}


def get_public_private_attribute_second(data, handle_type, db=None):
    public_keys = ['id', 'handle_code', 'handle_name', 'handle_type', 'user_id', 'rc_code',
                   'product_type', 'industry_type', 'link_website', 'module_sort', 'qr_code_logo_picture', 'parent_id']
    data['handle_type'] = handle_type
    print(data, 'data>>>>>')
    public_cols = {}
    attribute_data = []
    private_cols = {}
    reference_cols = []
    reference_handle = []  # 关联标识
    operate_type = False
    # 获取标识品类属性的关键字，类型，排序等
    sign_value = SignValue['sign_value'].value[handle_type]
    #新建创建id and crate_date
    if ('id' not in data) or data['id'] == '':
        data['id'] = str(uuid.uuid1())
        public_cols['create_date'] = get_cur_time()
        operate_type = True  # 表示新增
        private_cols['date'] = public_cols['create_date']
    for key in data:
        # 存放标识数据表
        if key in public_keys:
            public_cols[key] = data[key]
        # 处理需要保存到proxy和本地类目属性表的数据
        if key not in NO_ATTRIBUTE:
            print(key, 'key')
            create_dict = {
                'sign_key': key,
                'sign_type': sign_value[key]['sign_type'],
                'sign_value': data[key],
                'index': sign_value[key]['index'],
                'sign_name': sign_value[key]['sign_name']
            }
            attribute_data.append(create_dict)
        # 创建关联标识数据
        if key in ['category_handle_code', 'company_handle_code']:
            reference_cols.append({
                'id': str(uuid.uuid1()),
                'handle_id': data['handle_code'],
                'ref_handle_id': data[key],
                'ref_type': key
            })
            reference_handle.append(key)
    # 获取当前修改时间
    public_cols['modify_date'] = get_cur_time()
    # 组装保存到本地类目属性表的数据结构
    private_cols = {
        'id': str(uuid.uuid1()),
        'handle_id': public_cols['id'],
        'attribute_data': attribute_data,
        'modify_date': get_cur_time()
    }
    return {'public': public_cols, 'private': private_cols, 'operate_type': operate_type, 'reference_cols': reference_cols, 'reference_handle': reference_handle}


# 创建标识数据处理-存入代理解析服务器


def get_handle_to_proxy(data):
    res = {"value": []}
    # 普通标识值
    for x in data:
        value_dict = {
            'data': {
                'format': 'string',
                'value': json.dumps(x, ensure_ascii=False)
            },
            'references': [],
            'index': x['index'],
            'type': x['sign_type']
        }
        # # 判断是否引用标识
        # if x["sign_key"] in refer_handle and not x["sign_value"].strip() == '':  # 处理关联标识
        #     # print(refer_handle,'关联')
        #     value_dict['references'].append(
        #         {"index": REFERNCE_KEY[x["sign_key"]], "handle": x["sign_value"]})
        res['value'].append(value_dict)

    return res


def get_handle_id(db, handle_code):
    handle_mes = find_data(db, 'IDMIS_Handle', {'handle_code': handle_code})
    if len(handle_mes) > 0:
        return handle_mes[0]['id']


def get_company_info(data):
    if 'id' not in data.keys():
        data['id'] = str(uuid.uuid1())
        data['create_date'] = get_cur_time()
    data['modify_date'] = get_cur_time()
    return data


def request_handle_proxy(handle_code):
    '''递归函数，获取所有关联标识数据'''
    res = []
    data_dict = {}
    data_dict = requests.get(
        'http://idisif.gdsinsing.com:8080/'+handle_code).json()
    if data_dict['responseCode'] == 1 and len(data_dict["value"]) > 0:
        for sinle_dict in data_dict["value"]:
            res.append(json.loads(sinle_dict["data"]["value"]))
            if len(sinle_dict["references"]) > 0:
                for x in sinle_dict["references"]:
                    res = res + request_handle_proxy(x["handle"])
    return res
